package com.example.translationapp.viewmodel;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.translationapp.TransApp;
import com.example.translationapp.model.TransLationBean;
import com.example.translationapp.util.NetUtils;

import java.io.IOException;
import java.util.concurrent.Executors;

/**
 * Created by liuzhao.futrue on 2018/9/15.
 */

public class TranslationModel extends ViewModel {

    private MutableLiveData<TransLationBean> bean;

    private SharedPreferences preferences;

    public LiveData<TransLationBean> getTranslation() {
        preferences = TransApp.getApp().getSharedPreferences("trans", Context.MODE_PRIVATE);
        bean = new MutableLiveData<TransLationBean>();
        return bean;
    }

    public void save(String string){
        if (!TextUtils.isEmpty(string)) {
            String old = preferences.getString("translations", "单词");
            preferences.edit().putString("translations", old + "," + string).commit();
        }
    }


    public void loadTransLation(final String string) {
        if (TextUtils.isEmpty(string)) {
            Toast.makeText(TransApp.getApp(), "请输入内容", 0).show();
            return;
        }
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String result = NetUtils.executePost(string);
                    final TransLationBean jsonBean = JSON.parseObject(result, TransLationBean.class);
                    new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            bean.setValue(jsonBean);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
